package com.ruoyi.project.module.whd.diandan;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.library.api.RemoteLibraryService;
import com.ruoyi.library.api.domain.YhMsgInner;
import com.ruoyi.project.domain.YqgBarBills;
import com.ruoyi.project.domain.YqgConsumptionDetails;
import com.ruoyi.project.domain.YqgHands;
import com.ruoyi.project.domain.YqgInformationProject;
import com.ruoyi.project.service.IYqgBarBillsService;
import com.ruoyi.project.service.IYqgConsumptionDetailsService;
import com.ruoyi.project.service.IYqgHandsService;
import com.ruoyi.project.service.IYqgInformationProjectService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.ruoyi.common.security.utils.SecurityUtils.getLoginUser;

/**
 * 消费详细Controller
 * 
 * @author dr
 * @date 2023-04-17
 */
@RestController
@RequestMapping("/whd/diandan")
public class WhdDiandanController extends BaseController
{
    @Autowired
    private IYqgConsumptionDetailsService yqgConsumptionDetailsService;
    @Autowired
    private IYqgInformationProjectService yqgInformationProjectService;
    @Autowired
    private IYqgBarBillsService yqgBarBillsService;
    @Autowired
    private IYqgBarBillsService BarBillsService;
    @Autowired
    private IYqgHandsService yqgHandsService;
    @Autowired
    private RemoteLibraryService remoteLibraryService;
    /**
     * 查询消费详细列表
     */
    /*@RequiresPermissions("project:whd:diandan:list")*/
    @GetMapping("/list")
    public TableDataInfo list(YqgConsumptionDetails yqgConsumptionDetails)
    {
        startPage();
        List<YqgConsumptionDetails> list = yqgConsumptionDetailsService.selectYqgConsumptionDetailsList(yqgConsumptionDetails);
        return getDataTable(list);
    }
    /**
     * 查询吧台账单列表
     */
   /* @RequiresPermissions("project:whd:diandan:infolist")*/
    @GetMapping("/infolist")
    public void list(YqgBarBills yqgBarBills)
    {
        yqgBarBills.setHandState("1");
        List<YqgBarBills> list = yqgBarBillsService.selectYqgBarBillsList(yqgBarBills);
        for(int i=0;i<list.size();i++){
            System.out.println("手牌"+list.get(i).getHandBrand());
            System.out.println("开牌时间"+list.get(i).getOpeningTime());
            Date retime=DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",list.get(i).getOpeningTime()) ;
            LocalDateTime Record= LocalDateTime.ofInstant(retime.toInstant(), ZoneId.systemDefault());
            LocalDateTime newDateTime = Record.plusHours(22);
            LocalDateTime currentDateTime = LocalDateTime.now();
            System.out.println(currentDateTime.isAfter(newDateTime));
            System.out.println(currentDateTime.isBefore(newDateTime));
            if(currentDateTime.isAfter(newDateTime)){
                System.out.println("剩两小时了");
            }

        }

    }

    /**
     * 导出消费详细列表
     */
   /* @RequiresPermissions("project:whd:diandan:export")*/
    @Log(title = "消费详细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, YqgConsumptionDetails yqgConsumptionDetails)
    {
        List<YqgConsumptionDetails> list = yqgConsumptionDetailsService.selectYqgConsumptionDetailsList(yqgConsumptionDetails);
        ExcelUtil<YqgConsumptionDetails> util = new ExcelUtil<YqgConsumptionDetails>(YqgConsumptionDetails.class);
        util.exportExcel(response, list, "消费详细数据");
    }

    /**
     * 获取消费详细详细信息
     */
    /**
     * 获取手牌基础信息详细信息
     */
   /* @RequiresPermissions("project:whd:diandan:query")*/
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {

        YqgHands hands=new YqgHands();
        YqgBarBills yqgBarBills=new YqgBarBills();
        yqgBarBills.setHandBrand(id);
        yqgBarBills.setHandState("1");
//        yqgBarBills.setMergeStatus("1");
        List<YqgBarBills> blist = yqgBarBillsService.selectYqgBarBillsList(yqgBarBills);
        //判断输入手牌号

        hands.setHandBrand(id);
        /*hands.setHandState("0");*/
        List<YqgHands> wulist = yqgHandsService.selectYqgHandsList(hands);
        if(wulist.size()==0){
            return  new AjaxResult(500,id+"手牌不存在，请输入正确的手牌号");
        }else{
            if(blist.size()==0){
                return new AjaxResult(500,"手牌不在台,请输入在台手牌");
            }else{
                hands.setLockedState("0");
                List<YqgHands> list = yqgHandsService.selectYqgHandsList(hands);
                if(list.size()!=0){
                    return  new AjaxResult(500,id+"手牌已锁定，请解锁后使用");
                }else{
                    return  new AjaxResult(200,"");
                }
            }

     }


    }
    /**
     * 新增消费详细
     */
   /* @RequiresPermissions("project:whd:diandan")*/
    @Log(title="点单",businessType = BusinessType.INSERT,logicalKey = "handBrand")
    @PostMapping
    public AjaxResult add(@RequestBody YqgConsumptionDetails yqgConsumptionDetails)
    {
        //判空操作这里很重要
        /*if(yqgConsumptionDetails.getHandBrand()==null||yqgConsumptionDetails.getHandBrand().equals("")){
            return new AjaxResult(500,"手牌号为空不可下单");
        }*/
        LoginUser loginUser = getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        //服务员信息
        yqgConsumptionDetails.setUserId(sysUser.getUserId());
        yqgConsumptionDetails.setDeptId(sysUser.getDeptId());
        yqgConsumptionDetails.setNickName(sysUser.getNickName());
        yqgConsumptionDetails.setUserName(sysUser.getUserName());
        yqgConsumptionDetails.setPost(sysUser.getRemark());
        yqgConsumptionDetails.setDepartment("3");
        //根据手牌号与手牌状态判断唯一的在台手牌 并牌手牌不能消费
        YqgBarBills yqgBarBills=new YqgBarBills();
        yqgBarBills.setHandBrand(yqgConsumptionDetails.getHandBrand());
        yqgBarBills.setHandState("1");
//        yqgBarBills.setMergeStatus("1");
        List<YqgBarBills> list = yqgBarBillsService.selectYqgBarBillsList(yqgBarBills);
        //判断输入手牌号
       /* if(list.size()==0){
            return new AjaxResult(500,"手牌号输入错误");
        }*/
        yqgBarBills=list.get(0);
        //手牌信息
        yqgConsumptionDetails.setHandBrand(yqgBarBills.getHandBrand());
        yqgConsumptionDetails.setHandCategory(yqgBarBills.getHandCategory());
        yqgConsumptionDetails.setHandState(yqgBarBills.getHandState());
        yqgConsumptionDetails.setMergeStatus(list.get(0).getMergeStatus());
        yqgConsumptionDetails.setRetentionStatus(list.get(0).getRetentionStatus());
        yqgConsumptionDetails.setOriginalHand(list.get(0).getOriginalHand());

        //项目信息
        YqgInformationProject yqgInformationProject=new YqgInformationProject();
        yqgInformationProject.setProjectCode(yqgConsumptionDetails.getProjectCode());
        List<YqgInformationProject> Plist = yqgInformationProjectService.selectYqgInformationProjectList(yqgInformationProject);
        yqgInformationProject=Plist.get(0);
        yqgConsumptionDetails.setEntryName(yqgInformationProject.getEntryName());
        yqgConsumptionDetails.setProjectCategory(yqgInformationProject.getProjectCategory());
        yqgConsumptionDetails.setMnemonicCode(yqgInformationProject.getMnemonicCode());
        yqgConsumptionDetails.setUnit(yqgInformationProject.getUnit());
        yqgConsumptionDetails.setProjectCategory(yqgInformationProject.getProjectCategory());

        /*yqgConsumptionDetails.setUnitPrice(yqgInformationProject.getUnitPrice());*/
        yqgConsumptionDetails.setCommissionPrice(yqgInformationProject.getCommissionPrice());
        if(yqgConsumptionDetails.getProjectCategory().equals("01")){
            yqgBarBills.setOpeningTime(DateUtils.getTime());
            yqgBarBillsService.updateYqgBarBills(yqgBarBills);
        }

        yqgConsumptionDetails.setOpeningTime(DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",yqgBarBills.getOpeningTime()));
        //消费信息
        yqgConsumptionDetails.setRecordingTime(DateUtils.getNowDate());
        /*yqgConsumptionDetails.setQuantity("1");*/
       /* yqgConsumptionDetails.setTotalAmount(yqgInformationProject.getUnitPrice());*/
        //吧台信息
        yqgConsumptionDetails.setBarBillsId(yqgBarBills.getID());
        yqgConsumptionDetails.setTogether(yqgBarBills.getTogether());
        yqgConsumptionDetails.setBarBillsId(yqgBarBills.getID());
        yqgConsumptionDetails.setHandoverStatus("0");
        yqgConsumptionDetails.setSailingsSigns("0");
        /*System.out.println(yqgBarBills.getAllCost()!=null);
        if(!yqgBarBills.getAllCost().equals("0")){
            System.out.println("#####");
            long total=Long.valueOf(yqgBarBills.getAllCost());
            long shangpin=Long.valueOf(yqgInformationProject.getUnitPrice())*Long.valueOf(yqgConsumptionDetails.getQuantity());
            System.out.println("商品");
            System.out.println(shangpin);
            total=total+shangpin;
            System.out.println(total);
            yqgBarBills.setAllCost(String.valueOf(total));
        }
        else{
            System.out.println("!!!!!!!!");
            long total=Long.valueOf(yqgInformationProject.getUnitPrice())*Long.valueOf(yqgConsumptionDetails.getQuantity());
            System.out.println(total);
            yqgBarBills.setAllCost(String.valueOf(total));
        }*/
        yqgConsumptionDetails.setConsumptionStatus("0");
        yqgBarBills.setOperator(sysUser.getUserName());
        yqgBarBillsService.updateYqgBarBills(yqgBarBills);
        return toAjax(yqgConsumptionDetailsService.insertYqgConsumptionDetails(yqgConsumptionDetails));
    }

    /**
     * 修改消费金额
     */
   /* @RequiresPermissions("project:whd:diandan:edit")*/
    @Log(title = "消费详细", businessType = BusinessType.UPDATE)
    @PutMapping
    public void edit(@RequestBody YqgConsumptionDetails yqgConsumptionDetails)
    {
        LoginUser loginUser = getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        //根据手牌号与手牌状态判断唯一的在台手牌 并牌手牌不能消费
        YqgBarBills BarBills=new YqgBarBills();
        BarBills.setHandBrand(yqgConsumptionDetails.getHandBrand());
        BarBills.setHandState("1");
        List<YqgBarBills> list = BarBillsService.selectYqgBarBillsList(BarBills);
        BarBills=list.get(0);
        int total=gettotal(list.get(0));
        System.out.println("金额"+total);
        System.out.println(total+Integer.valueOf(yqgConsumptionDetails.getTotalAmount())>=500);
        try {
            Thread.sleep(500); // 延迟0.5秒钟执行
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
        if(total<500){
            if(total+Integer.valueOf(yqgConsumptionDetails.getTotalAmount())>=500){
                YhMsgInner msg=new YhMsgInner();
                msg.setMsgTitle("超费提醒");
                msg.setMsgContent("手牌号"+list.get(0).getHandBrand()+"的顾客，您的的点单金额已经超过500，请慎重消费。");
                msg.setSendUserName(sysUser.getUserName());//这里写发送者名字，填用户名就行，必填
                msg.setNote1(sysUser.getNickName());//这里填写发送者的昵称，对表的user表的nick_name，必填
                msg.setNote2("这里填写你业务的相对url，如/notice/noticelist，必填");
                List<String> receiveNames = new ArrayList<>();
                // 这里根据需要添加你要通知的用户名 可以有一个或多个 也就是user表的userName字段
                receiveNames.add(sysUser.getUserName());
                //调用服务
                remoteLibraryService.PushMag(msg,receiveNames);
            }
        }
       /* if(!BarBills.getAllCost().equals("0")){

            long total=Long.valueOf(BarBills.getAllCost());
            long shangpin=Long.valueOf(yqgConsumptionDetails.getTotalAmount());
            System.out.println("商品");
            System.out.println(shangpin);
            total=total+shangpin;
            System.out.println(total);
            BarBills.setAllCost(String.valueOf(total));
            System.out.println(BarBills);

            System.out.println("绍波最帅");
            if(total>500){
                System.out.println("执行");
            }
            try {
                Thread.sleep(500); // 延迟0.5秒钟执行
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }

            return  toAjax(BarBillsService.updateYqgBarBills(BarBills));
        }
        else{

            long total=Long.valueOf(yqgConsumptionDetails.getTotalAmount());
            System.out.println(total);
            BarBills.setAllCost(String.valueOf(total));
            try {
                Thread.sleep(500); // 延迟0.5秒钟执行
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
            if(total>500){
                System.out.println("执行");
            }
            return  toAjax(BarBillsService.updateYqgBarBills(BarBills));
        }*/

    }

    /**
     * 删除消费详细
     */
   /* @RequiresPermissions("project:whd:diandan:remove")*/
    @Log(title = "消费详细", businessType = BusinessType.DELETE)
	@DeleteMapping("/{IDs}")
    public AjaxResult remove(@PathVariable Long[] IDs)
    {
        return toAjax(yqgConsumptionDetailsService.deleteYqgConsumptionDetailsByIDs(IDs));
    }
    /**
     * 计算合计
     */
    public int gettotal(YqgBarBills yqgBarBills)
    {

        YqgConsumptionDetails ConsumptionDetails=new YqgConsumptionDetails();
        System.out.println(yqgBarBills.getID());
        System.out.println(yqgBarBills);
        yqgBarBills.setHandState("1");
        YqgBarBills BarBills=yqgBarBillsService.selectYqgBarBillsByID(yqgBarBills.getID());
        List<YqgConsumptionDetails> ylist=new ArrayList<>();
        if(BarBills.getRetentionStatus().equals("1")){
            ConsumptionDetails.setBarBillsId(BarBills.getID());

            ConsumptionDetails.setRetentionStatus("1");

            ylist = yqgConsumptionDetailsService.selectYqgConsumptionDetailsList(ConsumptionDetails);


        }else{
            ConsumptionDetails.setBeforeBarBillsId(BarBills.getID());


            //先查被留出去的记录
            List<YqgConsumptionDetails> llist = yqgConsumptionDetailsService.selectYqgConsumptionDetailsList(ConsumptionDetails);

            ConsumptionDetails.setBeforeBarBillsId(null);
            ConsumptionDetails.setBarBillsId(BarBills.getID());
            //再查自己的记录
            ylist = yqgConsumptionDetailsService.selectYqgConsumptionDetailsList(ConsumptionDetails);
            //过滤留进来的记录
            List<YqgConsumptionDetails> removelist=new ArrayList<>();
            for(int i=0;i<ylist.size();i++){
                if(ylist.get(i).getBeforeBarBillsId()==null){

                }else{
                    if (!ylist.get(i).getBeforeBarBillsId().equals(BarBills.getID())){
                        removelist.add(ylist.get(i));
                    }
                }

            }
            ylist.removeAll(removelist);
            if(llist.size()!=0){
                ylist.addAll(llist);
            }


        }
        int total=0;
        for (int i=0;i<ylist.size();i++){
            if(ylist.get(i).getConsumptionStatus().equals("0")){
                if(ylist.get(i).getEntryName().equals("过夜费")){
                    Date retime= ylist.get(i).getRecordingTime();
                    LocalDateTime Record= LocalDateTime.ofInstant(retime.toInstant(), ZoneId.systemDefault());
                    String date= DateUtils.dateTimeNow("yyyy-MM-dd");
                    String start=date+" 00:00:00";
                    String end=date+" 06:00:00";
                    Date startdate= DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",start);
                    Date enddate= DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",end);
                    LocalDateTime startTime= LocalDateTime.ofInstant(startdate.toInstant(), ZoneId.systemDefault());
                    LocalDateTime endTime = LocalDateTime.ofInstant(enddate.toInstant(), ZoneId.systemDefault());
                    if(Record.isAfter(startTime)&&Record.isBefore(endTime)){
                        LocalDateTime newDateTime = Record.plusHours(2);
                        LocalDateTime currentDateTime = LocalDateTime.now();
                        if(currentDateTime.isBefore(newDateTime)){
                            total=total+Integer.valueOf(ylist.get(i).getTotalAmount());
                        }

                    }
                    else{
                        total=total+Integer.valueOf(ylist.get(i).getTotalAmount());
                    }

                }
                else{
                    total=total+Integer.valueOf(ylist.get(i).getTotalAmount());
                }

            }

        }
        return total;
    }
}
